/**
 * @author Kevin.MOU Login view script Support
 */
(function($) {
	Login = {
		url : 'http://localhost',
		dataService : {},
		projects : {},
		currentProject : false,
		portal: $E.queryType === 'portal',
		verifyLock: $E.verifyLock,

		init : function() {
			var a = this;
			a.rsaPubKey = $('input#rsaPubKey').val();
			a.requestQueries = $.extend(true, a.defaultMode, Request.queryStrings());

			$('.login_remember').off('click').on('click', function(e) {
				e.preventDefault();
				$('#remember').toggleClass('checkbox_checked');
			});

			var form = $('form.login_form');
			if (Login.verifyAuth === 'image') {
				$('img.verifyCode', form).on('click', function(e) {
					//console.log('Change verify code')
					var src = $(this).attr('src');
					src = src.substring(0, src.lastIndexOf('&'));
					$(this).attr('src', src + '&t=' + Date.now())
				});
			} else if (Login.verifyAuth === 'sms') {
				$('button.verifyCode', form).on('click', function(e) {
					let epid = $("input#epid", form).val(),
						username = $("input#username", form).val(),
						password = $("input#password", form).val();
					if (! username)
						return a.showError('请输入用户登录名');

					$(".login_err_panel").hide();
					$F.await(function(go) {
						Ajax.post({
							url: Login.url + '/loginVerify_?t=' + Date.now(),
							data: {
								c: 'sms',
								uid: Login.uid,
								ecsid: 'ngs',
								epid: epid,
								username: username,
								password: $F.encPwd(password, Login),
								dbpool: '',
								ds: Login.dataService.key
							},
							success : function(data) {
								if (data.code > 0) {
									$F.info(data.message);
									makeVerifyState($(e.currentTarget))
								} else
									a.showError(data.message);
							},
							always: function() {
								go();
							}
						})
					});
				});
			}

			Login.verifier = $('div.login_verify', form);
			if (Login.verifyLock || Login.verifyAuthTrigger === 'always') {
				Login.verifier.show();
			} else {
				Login.verifier.appendTo($('body'));
			}

			form.on('submit', function(e) {
				e.preventDefault();
				var form = $("form.login_form"),
					epid = $("input#epid", form).val(),
					username = $("input#username", form).val(),
					group = $('select#group', form).val(),
					password = $("input#password", form).val(),
					verify = $("input#verify", form).val();

				$(".login_err_panel").hide();

				a.doLogin(epid, username, group, password, verify);
			});

			if (a.portal) {
				$('.login_epid').hide();
				$('.login_group').hide();
			} else {
				if (a.dataService.saas) {
					// SAAS模式登录
					if (!$E.epid) {
						$('.login_epid').show();
					}
					$('.login_group').hide();
				} else {
					// 传统模式登录
					$('.login_epid').hide();
					$('.login_group').show();
					// alert('Initialize login form as regular deployment');
					$('input#username').bind('blur', function(e) {
						a.loadProjects($('input#username').val());
					});
				}
			}


			var u, g, e;
			if (a.dataService.saas) {
				u = $.cookie("remember_username_saas");
				g = $.cookie("remember_group_saas");
				e = $.cookie("remember_epid_saas");
				if (!$E.epid) {
					$("input#epid").focus();
				} else {
					$("input#username").focus();
				}
			} else {
				u = $.cookie("remember_username");
				g = $.cookie("remember_group");
				$("input#username").focus();
			}
			if (u) {
				$("input#epid").val(e);
				$("input#username").val(u).trigger('blur');
				$('select#group').val(g);
				$("input#password").focus();
				$("#remember").forceClass("checkbox_checked");
			} else
				$("#remember").removeClass("checkbox_checked");

		},

		doLogin : function(epid, username, group, password, verify) {
			var a = this, remoteKey = localStorage.getItem("elite_remote_key");
			if (!remoteKey) {
				remoteKey = Guid.raw();
				localStorage.setItem("elite_remote_key", remoteKey);
			}

			if (Login.verifyAuth === 'slide') {
				SlideUnlocker.init({
					lang: Login.language,
					onLoad: function(callback) {
						Ajax.post({
							url: Login.url + '/slidelock.load_',
							data: {
								uid: Login.uid,
								ecsid: 'ngs'
							},
							dataType: 'binary',
							success: function(data) {
								callback(data);
							}
						})
					},
					onVerify : function(pos, callback) {
						Ajax.post({
							url: Login.url + '/slidelock.verify_',
							data: {
								uid: Login.uid,
								ecsid: 'ngs',
								pos: pos
							},
							success: function(data) {
								callback(data, function() {
									if (a.portal) {
										a.onPortalSubmit(epid, username, password, remoteKey, verify);
									} else {
										if (a.dataService.saas)
											a.onSubmitSAAS(epid, username, password, remoteKey, verify);
										else
											a.onSubmit(username, group, password, remoteKey, verify);
									}
								});
							}
						})
					}
				});
			} else {
				if (a.portal) {
					a.onPortalSubmit(epid, username, password, remoteKey, verify);
				} else {
					if (a.dataService.saas)
	                    a.onSubmitSAAS(epid, username, password, remoteKey, verify);
	                else
	                    a.onSubmit(username, group, password, remoteKey, verify);
				}
			}
		},

		onSubmitSAAS : function(epid, username, password, remoteKey, verify) {
			if (epid == '')
				epid = 'MainDB';
			else
				epid = epid.toUpperCase();

			var a = this, busyId = busyShow();
			var dataRequest = $.extend(a.requestQueries, {
				uid: a.uid,
				captcha: verify,
				language: a.language,
				ecsid: 'ngs',
				payload: JSON.stringify({
					useLang: a.language,
					standFlag: 0,
					cacheFlag: 1,
					clientFlag: 2,
					epid : epid,
					loginId : username,
					password : $F.encPwd(password, a),
					remoteInfo : remoteKey,
					subProjectList : [],
					projects : [],
					uid: a.uid
				})
			});

			Ajax.post({
				url : a.url + '/login_?device=mobile',
				data : dataRequest,
				success : function(data) {
					if ($("#remember").hasClass("checkbox_checked")) {
						$.cookie("remember_username_saas", username, {
							expires : 30,
							path : '/'
						});
						$.cookie("remember_epid_saas", epid, {
							expires : 30,
							path : '/'
						});
						$.cookie('remember_password_saas', password, {
							expires : 30,
							path : '/'
						});
					} else {
						$.cookie("remember_username_saas", null, {path : '/'});
						$.cookie("remember_epid_saas", null, {path : '/'});
						$.cookie('remember_password_saas', null, {path : '/'});
					}
					if (data.code > 0) {
						location.href = data.message;
					} else {
						refreshVerify();

						if (data.code == -7 && a.forceLoginAllow) {
							Helper.busyHide(busyId);
							$F.confirm('当前账户已经被登录，是否需要强制登录？<br/>强制登录将踢出现有登录状态', function(){
								a.onForceSubmit(data.value);
							}, undefined, undefined, true);
						} else
							a.showError(data.message);
					}
				},
				always : function() {
					Helper.busyHide(busyId);
				}
			});
		},

		onSubmit : function(username, group, password, remoteKey, verify) {
			var a = this, projects = [];

			if (! group && $E.loginInfoType != 2) {
				$('select#group').focus();
				return a.showError('未选择登录的组');
			}

			projects.push({
				prjId : a.currentProject.id,
				prjName : a.currentProject.name,
				groupId : group,
				dbPool : a.currentProject.key
			});

			var dataRequest = $.extend(a.requestQueries, {
				uid: a.uid,
				captcha: (verify ? verify.toUpperCase() : ''),
				language: a.language,
				ecsid: 'ngs',
				payload: JSON.stringify({
					useLang: a.language,
					standFlag: 1,
					cacheFlag: 1,
					clientFlag: 2,
					epid : '',
					loginId : username,
					password : $F.encPwd(password, a),
					remoteInfo : remoteKey,
					subProjectList : [],
					projects : projects,
					uid: a.uid
				})
			});

			var busyId = busyShow();
			Ajax.post({
				url : a.url + '/login_?device=mobile',
				data : dataRequest,
				success : function(data) {
					if ($("#remember").hasClass("checkbox_checked")) {
						$.cookie("remember_username", username, {
							expires : 30,
							path : '/'
						});
						$.cookie("remember_group", group, {
							expires : 30,
							path : '/'
						});
					} else {
						$.cookie("remember_username", null, {path : '/'});
						$.cookie("remember_group", null, {path : '/'});
					}
					if (data.code > 0) {
						location.href = data.message;
					} else {
						refreshVerify();

						if (data.code == -7 && a.forceLoginAllow) {
							$F.confirm('当前账户已经被登录，是否需要强制登录？<br/>强制登录将踢出现有登录状态', function(){
								a.onForceSubmit(data.value);
							}, undefined, undefined, true)
						} else {
							setTimeout(function(){
								$('input#username').focus();
							}, 10);
							a.showError(data.message);
						}
					}
				},
				always : function() {
					Helper.busyHide(busyId);
				}
			});
		},

		onPortalSubmit : function(epid, username, password, remoteKey, verify) {
			var a = this, projects = [];

			if (a.dataService.saas) {
				if (epid === '')
					epid = 'MainDB';
				else
					epid = epid.toUpperCase();
			} else {
				epid = '';
				projects.push({
					prjId : a.currentProject.id,
					prjName : a.currentProject.name,
					groupId : '',
					dbPool : a.currentProject.key
				});
			}

			var dataRequest = $.extend(a.requestQueries, {
				uid: a.uid,
				captcha: (verify ? verify.toUpperCase() : ''),
				language: a.language,
				ecsid: 'ngs',
				payload: JSON.stringify({
					useLang: a.language,
					standFlag: 1,
					cacheFlag: 1,
					clientFlag: 2,
					epid : epid,
					loginId : username,
					password : $F.encPwd(password, a),
					remoteInfo : remoteKey,
					subProjectList : [],
					projects : projects,
					uid: a.uid
				})
			});

			var busyId = busyShow();
			Ajax.post({
				url : a.url + '/portal/m/login_?ds=' + a.dataService.key,
				data : dataRequest,
				success : function(data) {
					if ($("#remember").hasClass("checkbox_checked")) {
						$.cookie("remember_username", username, {
							expires : 30,
							path : '/'
						});
						$.cookie('remember_password', password, {
							expires : 30,
							path : '/'
						});
					} else {
						$.cookie("remember_username", null, {path : '/'});
						$.cookie('remember_password', null, {path : '/'});
					}
					if (data.code > 0) {
						location.href = Login.url + '/m/';
					} else {
						refreshVerify();

						if (data.code == -7 && a.forceLoginAllow) {
							$F.confirm('当前账户已经被登录，是否需要强制登录？<br/>强制登录将踢出现有登录状态', function(){
								a.onForceSubmit(data.value);
							}, undefined, undefined, true)
						} else {
							setTimeout(function(){
								$('input#username').focus();
							}, 10)
							a.showError(data.message);
						}
					}
				},
				always : function() {
					Helper.busyHide(busyId);
				}
			});
		},

		onForceSubmit : function(forceId) {
			var a = this, busyId = busyShow();
			var dataRequest = $.extend(a.requestQueries, {
				language: a.language,
				ds: a.dataService.key,
				forceId: forceId,
				uid: a.uid,
				ecsid: 'ngs'
			});
			Ajax.post({
				url : a.url + '/loginForce_?device=mobile',
				data : dataRequest,
				success : function(data) {
					//console.log(data);
					if (data.code > 0) {
						location.href = data.message;
					} else
						a.showError(data.message);
				},
				fail : function(jqXHR, textStatus, errorThrown) {
					a.showError(textStatus);
					Helper.busyHide(busyId);
				}
			})
		},

		showError : function(e) {
			$("#err_tips").text(e);
			$(".login_err_panel").show();
		},

		loadProjects : function(username) {
			if (!username) {
				return;
			}
			if($E.loginInfoType == 2) {
				this.currentProject = {};
				$('.login_group').hide();
			}
			var a = this, busyId = busyShow(), data = JSON.stringify({
				operate : 'StandProject',
				epid : a.dataService.dbPool,
				loginName : username
			});
			a.currentProject = false;
			Ajax.post({
				url : $E.loginInfoType == 1 ? $E.url + '/loginInfo' : getServiceMethod('LoginInfo'),
				data : data,
				headers : {
					THREADID: Date.now(),
					DS: a.dataService.key,
					SIGNER: md5(data)
				},
				contentType : 'json',
				success : function(data, textStatus, jqXHR) {
					if (data.code > 0) {
						data.value = Ajax.d(data.value, jqXHR);
						// console.log(data.value);
						a.projects = {};
						$.each(data.value.fields, function(i, v) {
							if (!a.projects[v[0]]) {
								a.projects[v[0]] = {};
								a.projects[v[0]].groups = [];
							}
							a.projects[v[0]].id = v[0];
							a.projects[v[0]].name = v[1];
							a.projects[v[0]].key = v[5];
							a.projects[v[0]].groups.push({
								label : v[3],
								value : v[2]
							})
						});

						var projExists = false;
						for ( var key in a.projects) {
							if (projExists)
								break;

							projExists = true;
							a.currentProject = a.projects[key];
							var sg = $('select#group').empty();
							$.each(a.currentProject.groups, function() {
								sg.append('<option value="' + this.value + '">' + this.label + '</option>');
							})
						}
						if (! projExists)
							return alert('No project defined.');

					} else {
						// a.showError(data.message);
						// $('input#username').select().focus();
					}
				},
				always : function() {
					Helper.busyHide(busyId);
				}
			});
		}
	};

	var busyShow = function() {
		var busyId = Guid.raw();
		Helper.busyShow('', busyId, {
			opacity : '.5', // 遮布透明度
			color : '#fff',
			background : '#444',
			fontSize : '2em',
			boxShadow : '2px 6px 12px rgba(0, 0, 0, 0.5)' // 对话框阴影
		});
		return busyId;
	},

	getMapSize = function(map) {
		var size = 0;
		for ( var key in map) {
			size++;
		}
		return size;
	},

	getServiceMethod = function(method) {
		var serviceUrl = Login.dataService.url;
		if (serviceUrl.toLowerCase().startWith('http')) {
            return Login.url + '/proxy?method=' + method;
		} else {
			// 直接访问同一个JVM下的其他WebApp服务
			return method? (serviceUrl + '/' + method) : serviceUrl;
		}
	},

	refreshVerify = function() {
		if (Login.verifyAuthTrigger === 'onerror') {
			Login.verifyLock = true;
			$('div.login_password').after(Login.verifier.show());
		}
		if (Login.verifyAuth === 'image') {
			$('img.verifyCode').click();
			$('input#verify').val('');
		}
	},

	makeVerifyState = function(t) {
		t.attr('disabled', true);
		t.forceClass('disabled');
		var wait = function(v) {
			t.text(v + Language.verifyProcess);
			v --;
			if (v > 0)
				setTimeout(function(){
					wait(v)
				}, 1000);
			else
				t.removeClass('disabled').attr('disabled', false).text(Language.verify);
		};
		wait(60);
	};

	$(function() {
		Login.url = $E.url;
		Login.jsv = $E.jsv;
		Login.forceLoginAllow = $E.forceLoginAllow;
		Login.enc = $E.enc;
		Login.pwdEncWithRSA = $E.pwdEncWithRSA;
		Login.verifyAuth = $E.verifyAuth;
		Login.verifyAuthTrigger = $E.verifyAuthTrigger;
		Login.dataService = $E.dataService;
		Login.defaultMode = $E.defaultMode;
		Login.uid = $E.uid;
		Login.language = $E.language;
		Login.init();
	});
})(jQuery);
